<template>
  <basic-container>
    <el-container>
      <el-aside width="200px">
        <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick"></avue-tree>
      </el-aside>
      <el-main style="margin-left: 10px">
        <avue-crud
          :option="option"
          :table-loading="loading"
          :data="data"
          ref="crud"
          v-model="form"
          :page.sync="page"
          :permission="permissionList"
          @row-del="rowDel"
          @search-change="searchChange"
          @search-reset="searchReset"
          @selection-change="selectionChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="onLoad(page, query)"
          @on-load="onLoad"
        >
          <template slot="menuLeft">
            <el-button type="primary" v-if="permission.wf_design_model_add" @click="handleDesign({})"> 新增 </el-button>
            <el-button type="success" v-if="permission.wf_design_model_change_category" @click="handleChangeCategory">
              更改分类
            </el-button>
          </template>
        </avue-crud>
      </el-main>
    </el-container>

    <el-dialog :visible.sync="categoryVisible" append-to-body title="选择分类">
      <avue-form
        v-model="form"
        :option="{
          column: [
            {
              type: 'tree',
              label: '流程分类',
              span: 24,
              props: { label: 'name', value: 'id' },
              prop: 'category',
              dicUrl: '/api/blade-workflow/design/category/tree',
              required: true,
              rules: [{ required: true, message: '请选择分类' }]
            }
          ]
        }"
        @submit="handleDeploySubmit"
      ></avue-form>
    </el-dialog>

    <user-option ref="userOption" :user-option="userOption" @submit="handleScopeSubmit"></user-option>

    <!-- <el-drawer title="流程设计" :visible.sync="drawerVisile" direction="rtl" size="90%" append-to-body>
      <DesignIndex :param="row.id || 0"></DesignIndex>
    </el-drawer> -->
  </basic-container>
</template>

<script>
import { getList, remove, deploy, changeCategory, getDetail } from '@/api/plugin/workflow/model'
import { getList as scopeList, submit as scopeSubmit } from '@/api/plugin/workflow/model-scope'
import { tree } from '@/api/plugin/workflow/category'

import { mapGetters } from 'vuex'

import UserOption from '../process/components/user-option.vue'
import DesignIndex from './index'

export default {
  components: { UserOption, DesignIndex },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        size: 'mini',
        height: 'auto',
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        selection: true,
        dialogType: 'drawer',
        align: 'center',
        searchMenuSpan: 6,
        menuWidth: 120,
        column: [
          {
            label: '模型key',
            prop: 'modelKey',
            overHidden: true,
            search: true
          },
          {
            label: '模型名称',
            prop: 'name',
            overHidden: true,
            search: true
          },
          {
            label: '分类',
            prop: 'categoryId',
            type: 'tree',
            props: {
              label: 'name',
              value: 'id'
            },
            dicData: [],
            rules: [
              {
                required: true,
                message: '请选择分类',
                trigger: 'change'
              }
            ]
          },
          {
            label: '描述',
            prop: 'description',
            overHidden: true
          },
          {
            label: '版本',
            prop: 'version',
            width: 80
          }
        ],
        operatingButtons: this.getOperatingButtons
      },
      data: [],
      row: '',
      categoryVisible: false,
      userOption: {
        userUrl: '/api/blade-user/search/user',
        roleUrl: '/api/blade-system/search/role',
        deptUrl: '/api/blade-system/search/dept',
        postUrl: '/api/blade-system/search/post'
      },
      treeData: [],
      treeOption: {
        size: 'mini',
        addBtn: false,
        props: {
          label: 'name',
          value: 'id'
        }
      },
      drawerVisile: false
    }
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.wf_design_model_add, false),
        viewBtn: this.vaildData(this.permission.wf_design_model_view, false),
        delBtn: this.vaildData(this.permission.wf_design_model_delete, false),
        editBtn: this.vaildData(this.permission.wf_design_model_edit, false)
      }
    },
    ids() {
      let ids = []
      this.selectionList.forEach(ele => {
        ids.push(ele.id)
      })
      return ids.join(',')
    }
  },
  mounted() {
    this.getCategoryList()
  },
  methods: {
    getOperatingButtons() {
      const design = { text: '设计', callback: this.handleDesign }
      const deploy = { text: '部署', callback: this.handleDeploy }
      const history = { text: '历史', callback: this.handleHistory }
      const scope = { text: '权限', callback: this.handleScope }
      const copy = { text: '拷贝', callback: this.handleCopy }

      let buttons = []
      if (this.permission.wf_design_model_design) buttons.push(design)
      if (this.permission.wf_design_model_deploy) buttons.push(deploy)
      if (this.permission.wf_design_model_history) buttons.push(history)
      if (this.permission.wf_design_model_scope) buttons.push(scope)
      if (this.permission.wf_design_model_copy) buttons.push(copy)
      return buttons
    },
    handleCopy(row) {
      getDetail(row.id).then(res => {
        const { xml } = res.data.data
        this.$Clipboard({
          text: xml
        })
          .then(() => {
            this.$message.success('拷贝xml成功')
          })
          .catch(() => {})
      })
    },
    handleChangeCategory() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.categoryType = 'change'
      this.categoryVisible = true
    },
    getCategoryList() {
      tree().then(res => {
        const data = res.data.data
        this.findObject(this.option.column, 'categoryId').dicData = this.deepClone(data)

        this.treeData = data
        this.treeData.unshift({ id: '', name: '全部' })
      })
    },
    nodeClick({ id }) {
      this.categoryId = id
      this.searchChange(this.query)
    },
    handleScopeSubmit(list) {
      list.forEach(l => (l.val = l.value))

      const { id, modelKey } = this.row
      const param = {
        modelId: id,
        modelKey,
        scopeList: list
      }
      scopeSubmit(param).then(() => {
        this.$message.success('操作成功')
      })
    },
    handleScope(row) {
      scopeList({ modelId: row.id }).then(res => {
        this.$set(
          this.userOption,
          'data',
          res.data.data.map(d => {
            return {
              value: d.val,
              text: d.text,
              type: d.type
            }
          })
        )
        this.row = row
        this.$refs.userOption.visible = true
      })
    },
    handleDeploySubmit(form, done) {
      const { id, category } = form
      if (this.categoryType == 'change') {
        changeCategory({ ids: this.ids, category }).then(() => {
          this.$message.success('修改成功')
          this.categoryType = ''
          done()
          this.categoryVisible = false
          this.onLoad(this.page, this.query)
        })
      } else {
        deploy({ id, category }).then(() => {
          this.$message.success('部署成功')
          done()
          this.categoryVisible = false
        })
      }
    },
    handleDeploy(row) {
      this.form.id = row.id
      this.categoryVisible = true
    },
    handleDesign(row) {
      // this.$router.push('/workflow/design/process/' + (row.id || 0))

      this.$quickDrawer({
        title: '流程设计',
        width: '90%',
        component: require('@/views/plugin/workflow/design/index').default,
        props: { param: row.id || 0 },
        on: {
          refresh: () => {
            this.onLoad(this.page)
          }
        }
      })
      // this.row = row
      // this.drawerVisile = true
    },
    handleHistory(row) {
      // this.$router.push('/workflow/design/model/history/' + row.id)

      this.$quickDrawer({
        title: '模型历史',
        width: '90%',
        component: require('@/views/plugin/workflow/design/model-history').default,
        props: { param: row.id || 0, permission: this.permission },
        on: {
          refresh: () => {
            this.onLoad(this.page)
          }
        }
      })
    },
    rowDel(row) {
      this.$confirm('删除全部版本或者回退到最后版本?', {
        distinguishCancelAndClose: true,
        confirmButtonText: '回退',
        cancelButtonText: '全部删除',
        type: 'warning'
      })
        .then(() => {
          const param = {
            id: row.id,
            rollback: true
          }
          remove(param).then(() => {
            this.onLoad(this.page)
            this.$message.success('操作成功')
          })
        })
        .catch(action => {
          if (action == 'cancel') {
            const param = {
              id: row.id,
              rollback: false
            }
            remove(param).then(() => {
              this.onLoad(this.page)
              this.$message.success('操作成功')
            })
          }
        })
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据')
        return
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove({ id: this.ids })
        })
        .then(() => {
          this.onLoad(this.page)
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.$refs.crud.toggleSelection()
        })
    },
    searchReset() {
      this.query = {}
      this.onLoad(this.page)
    },
    searchChange(params, done) {
      this.query = params
      this.onLoad(this.page, params)
      if (done && typeof done == 'function') done()
    },
    selectionChange(list) {
      this.selectionList = list
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize
    },
    onLoad(page, params = {}) {
      this.loading = true

      if (this.categoryId) params['categoryId_equal'] = this.categoryId
      else delete params['categoryId_equal']

      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data
        this.page.total = data.total
        this.data = data.records
        this.loading = false
      })
    }
  }
}
</script>

<style></style>
